package com.mf.basic.services;

import cn.dev33.satoken.stp.StpUtil;
import com.mf.basic.entity.DtoSet;
import com.mf.basic.enums.EnumBaseParams;
import com.mf.basic.mapper.MapperSet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Luke on 2025/3/8 17:03.
 */
@Service
@Transactional
public class ServiceSet extends ServiceImpl<MapperSet, DtoSet> implements BaseService<DtoSet>{
    @Override
    public LambdaQueryWrapper<DtoSet> fillParams(Map<String, Object> params) {
        return loadQw().orderByDesc(DtoSet::getShowOrder);
    }

    /**
     * 保存
     * @param set 设置对象
     */
    public synchronized void doSave(DtoSet set){
        findCheckById(Math.toIntExact(set.getId()), true);
        String douser = (String) StpUtil.getSession().get(EnumBaseParams.douser.name());
        set.setDouser(douser).setDotime(null).setUptime(null).setSetMark(null).setSetKey(null);
        this.updateById(set);
    }

    /**
     * 根据setKey查询
     * @param setKey key,多个以,号分隔
     * @return Map<String, DtoSet>
     */
    public Map<String, DtoSet> findBySetKey(String setKey){
        LambdaQueryWrapper<DtoSet> qw = loadQw();
        if(setKey != null && !setKey.trim().isEmpty()){
            HashSet<String> keySet = new HashSet<>(Arrays.asList(setKey.split(",")));
            if(keySet.size() == 1){
                qw.eq(DtoSet::getSetKey, setKey);
            }else{
                qw.in(DtoSet::getSetKey, keySet);
            }
        }
        qw.orderByDesc(DtoSet::getShowOrder);
        List<DtoSet> list = this.list(qw);
        if(CollectionUtils.isEmpty(list)){
            return new HashMap<>();
        }
        return list.stream().collect(Collectors.toMap(DtoSet::getSetKey, d -> d));
    }

}
